# api/preview_routes.py
from flask import Blueprint, request, jsonify, send_file
from database import PreviewDAO
from file_manager import PreviewManager
import uuid
import json
import os
from utils.logger import get_logger

logger = get_logger(__name__)

def create_preview_routes(preview_dao: PreviewDAO, preview_manager: PreviewManager):
    """创建预览相关路由"""

    preview_bp = Blueprint('preview', __name__)

    @preview_bp.route('/generate-preview', methods=['POST'])
    def generate_preview():
        """生成参数预览图"""
        try:
            data = request.get_json()
            human_file_id = data.get('human_file_id')
            background_file_id = data.get('background_file_id')
            params = data.get('params', {})

            if not human_file_id or not background_file_id:
                return jsonify({'success': False, 'message': '缺少必要参数'})

            # 这里需要通过DAO获取文件路径
            # 简化实现，实际需要注入upload_dao
            from database import UploadDAO, Database
            db = Database()
            upload_dao = UploadDAO(db)

            human_upload = upload_dao.get_upload_by_id(human_file_id)
            bg_upload = upload_dao.get_upload_by_id(background_file_id)

            if not human_upload or not bg_upload:
                return jsonify({'success': False, 'message': '文件不存在'})

            # 生成预览
            preview_id = str(uuid.uuid4())
            preview_path = preview_manager.create_preview(
                preview_id, human_upload['file_path'], bg_upload['file_path'], params
            )

            if preview_path:
                # 保存预览记录到数据库
                success = preview_dao.save_preview(
                    preview_id, human_file_id, background_file_id,
                    preview_path, json.dumps(params)
                )

                if success:
                    return jsonify({
                        'success': True,
                        'preview_id': preview_id,
                        'preview_url': f'/api/preview-image/{preview_id}'
                    })
                else:
                    return jsonify({'success': False, 'message': '保存预览记录失败'})
            else:
                return jsonify({'success': False, 'message': '生成预览失败'})

        except Exception as e:
            logger.error(f"生成预览失败: {e}")
            return jsonify({'success': False, 'message': f'生成预览失败: {str(e)}'})

    @preview_bp.route('/preview-image/<preview_id>')
    def get_preview_image(preview_id):
        """获取预览图片"""
        preview_path = preview_manager.get_preview_path(preview_id)

        if preview_path and os.path.exists(preview_path):
            return send_file(preview_path)
        else:
            return jsonify({'error': '预览图不存在'}), 404

    @preview_bp.route('/clear-preview/<preview_id>', methods=['DELETE'])
    def clear_preview(preview_id):
        """清除指定预览"""
        try:
            # 删除文件
            success = preview_manager.delete_preview(preview_id)

            if success:
                # 从数据库中删除记录
                preview_dao.delete_preview(preview_id)
                return jsonify({'success': True, 'message': '预览已清除'})
            else:
                return jsonify({'success': False, 'message': '清除预览失败'})

        except Exception as e:
            logger.error(f"清除预览失败: {e}")
            return jsonify({'success': False, 'message': '清除预览失败'})

    return preview_bp